import React, {useState} from "react";
import {Select} from "antd";
import {isEmptyObj} from "../../../../util/typeUitl";
import {http} from "../../../../util/httpService";
import {TableApiType} from "../DataType";

const {Option} = Select

interface SelectType {
    InputConfig?: Object
    InputValueConfig: any
}

interface SelectItemsType {
    id: any,
    name: any
}

function SelectItems(props: SelectType) {
    const {InputConfig} = props
    const [childrenItems, setChildrenItems] = useState<Array<SelectItemsType>>([]);
    React.useEffect(() => {
        let items: Array<any> = []
        const {childrenItem = [], keyName, keyValue, tableApi} = props.InputValueConfig
        if (childrenItem.length > 0) {
            items = childrenItem
            setChildrenItems(items)
        } else if (!isEmptyObj(tableApi)) {
            getChildItem(tableApi, keyName, keyValue)
        }
    }, [props.InputValueConfig])

    const getChildItem = async (tableApi: TableApiType, keyName: string = 'name', keyValue: string = 'id') => {
        const {url, type, isApi, params} = tableApi
        let items: Array<SelectItemsType> = []
        const data = (await http(url, params, isApi, type)).data.data
        data.forEach((item: any) => {
            items.push({id: item[keyValue], name: item[keyName]})
        })
        setChildrenItems(items)
    }

    return (
        <Select {...InputConfig}>
            {childrenItems.map((item: SelectItemsType) => {
                return <Option key={item.id} value={item.id}>{item.name}</Option>
            })}
        </Select>
    )
}

export default SelectItems